package org.dfg.corejava.jdk6.httpserver;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

/**
 * 实现一个Http服务器
 * @author DingFugui
 */
public class HTTPServerAPITester {
	public static void main(String[] args) {
		try {
			HttpServer hs = HttpServer.create(new InetSocketAddress(8888), 0);// 设置HttpServer的端口为8888
			hs.createContext("/test", new MyHandler());// 用MyHandler类内处理到/chinajash的请求
			hs.setExecutor(null); // creates a default executor
			hs.start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

class MyHandler implements HttpHandler {
	public void handle(HttpExchange t) throws IOException {
		// InputStream is = t.getRequestBody();
		String response = "<p>hello</p>";
		t.sendResponseHeaders(200, response.length());
		OutputStream os = t.getResponseBody();
		os.write(response.getBytes());
		os.close();
	}
}